package accessingdatajpa.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * @Author: haoljh
 * @Description:
 * @Date: 2019-04-16 10:19
 */
public class NcOccTransferUtils {

    public static void copyProperties(Object source, Object dest) throws Exception{
        // set目标对象值
        Class sourceClass = source.getClass();
        Field[] sourceDeclaredFields = sourceClass.getDeclaredFields();
        Method[] sourceMethods = sourceClass.getMethods();
        Class destClass = dest.getClass();
        Field[] destDeclaredFields = destClass.getDeclaredFields();
        for (Field destField : destDeclaredFields){
            boolean isFinal = Modifier.isFinal(destField.getModifiers());
            if (isFinal){
                String fieldName = destField.getName();
                String fieldValue = (String)destField.get(null);
                for(Field sourceField : sourceDeclaredFields){
                    String name = sourceField.getName();
                    if (name.equals(fieldValue)){
                        for (Method sourceMethod : sourceMethods){
                            if (("get"+name).toLowerCase().equals(sourceMethod.getName().toLowerCase())){
                                Object invoke = sourceMethod.invoke(source);
                                String setMetStr = "set" + fieldValue.substring(0,1).toUpperCase()+fieldName.substring(1);
                                Method setMethod =  destClass.getDeclaredMethod(setMetStr, new Class[]{destField.getType()});
                                setMethod.invoke(dest, invoke);
                                break;
                            }
                        }
                        break;
                    }
                }
            }
        }
    }

}
